﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using Emgu.CV;
    using Emgu.CV.CvEnum;
    using Emgu.CV.Structure;
    using Emgu.CV.Util;
namespace WinFormsApp1
{


    public class WhiteRegionDetector2
    {
        /// <summary>
        /// 在指定区域内查找接近白色的连续区域
        /// </summary>
        /// <param name="imagePath">图像路径</param>
        /// <param name="searchArea">搜索区域（矩形范围）</param>
        /// <param name="colorThreshold">颜色阈值（0-255，值越小颜色要求越严格）</param>
        /// <param name="minArea">最小区域面积（像素数）</param>
        /// <returns>找到的白色区域坐标列表（矩形边界）</returns>
        public static List<Rectangle> FindWhiteRegionsInArea(
            string imagePath,
            Rectangle searchArea,
            int colorThreshold = 30,
            int minArea = 5)
        {
            List<Rectangle> results = new List<Rectangle>();

            using (Mat src = CvInvoke.Imread(imagePath, ImreadModes.Color))
            {
                if (src.IsEmpty)
                    throw new ArgumentException("无法加载图像");

                // 限定搜索区域在图像范围内
                searchArea.Intersect(new Rectangle(0, 0, src.Width, src.Height));

                // 提取ROI区域
                using (Mat roi = new Mat(src, searchArea))
                {
                    // 转换为HSV颜色空间
                    Mat hsv = new Mat();
                    CvInvoke.CvtColor(roi, hsv, ColorConversion.Bgr2Hsv);

                    // 定义白色范围（H:任意，S:低饱和度，V:高亮度）
                    ScalarArray lower = new ScalarArray(new MCvScalar(0, 0, 255 - colorThreshold));
                    ScalarArray upper = new ScalarArray(new MCvScalar(180, colorThreshold, 255));

                    // 创建颜色掩模
                    Mat mask = new Mat();
                    CvInvoke.InRange(hsv, lower, upper, mask);

                    // 形态学处理（去除噪点）
                    Mat kernel = CvInvoke.GetStructuringElement(ElementShape.Ellipse, new Size(3, 3), new Point(-1, -1));
                    CvInvoke.MorphologyEx(mask, mask, MorphOp.Open, kernel, new Point(-1, -1), 1, BorderType.Default, default);

                    // 查找轮廓
                    VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
                    CvInvoke.FindContours(mask, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);

                    // 处理找到的轮廓
                    for (int i = 0; i < contours.Size; i++)
                    {
                        double area = CvInvoke.ContourArea(contours[i]);
                        if (area >= minArea)
                        {
                            // 获取相对坐标并转换为绝对坐标
                            Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);
                            rect.Offset(searchArea.X, searchArea.Y);
                            results.Add(rect);
                        }
                    }
                }
            }
            return results;
        }

        /// <summary>
        /// 可视化检测结果
        /// </summary>
        public static void VisualizeResult(
            string inputPath,
            string outputPath,
            List<Rectangle> regions,
            Rectangle searchArea)
        {
            using (Mat src = CvInvoke.Imread(inputPath))
            {
                // 绘制搜索区域边界
                CvInvoke.Rectangle(src, searchArea, new MCvScalar(255, 0, 0), 2);

                // 绘制检测结果
                foreach (var rect in regions)
                {
                    CvInvoke.Rectangle(src, rect, new MCvScalar(0, 255, 0), 1);
                }

                CvInvoke.Imwrite(outputPath, src);
            }
        }

        // 使用示例
        public static void Main4(string b)
        {
            try
            {
                string input = b;
                string output = "output.jpg";

                // 定义搜索区域（x, y, width, height）
                Rectangle searchArea = new Rectangle(0, 0, 300, 150);

                // 查找白色区域（颜色阈值30，最小面积5像素）
                var regions = FindWhiteRegionsInArea(input, searchArea, 30,1);

                // 可视化结果
                VisualizeResult(input, output, regions, searchArea);

                Console.WriteLine($"在指定区域内找到 {regions.Count} 个白色区域");
                Console.WriteLine("结果已保存至: " + output);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }
    }
}
